package com.navi.mould1.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;


@RestController
public class ExcelController {
    @RequestMapping(value = "/exportExcel.do")
    public void export(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Calendar now = Calendar.getInstance();
        SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMMddHHmmss");
        request.setCharacterEncoding("UTF-8");
        String title = request.getParameter("title");
        String data = request.getParameter("data");
        ObjectMapper om = new ObjectMapper();
        String[][] matrix = om.readValue(data, String[][].class);
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        for (int i = 0; i < matrix.length; i++) {
            XSSFRow row = sheet.createRow(i);
            for (int j = 0; j < matrix[i].length; j++) {
                XSSFCell cell = row.createCell(j);
                cell.setCellValue(matrix[i][j]);
            }
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        workbook.write(baos);
        baos.flush();
        baos.close();
        response.reset();
        response.addHeader("Content-Disposition", "attachment;filename="+ new String(title.getBytes(), "ISO-8859-1") + tempDate.format(now.getTime()) + ".xlsx");
        response.addHeader("Content-Length", String.valueOf(baos.size()));
        response.setContentType("application/vnd.ms-excel");
        response.getOutputStream().write(baos.toByteArray());
    }
}
